/** 选择本地文件中的Excel文件 */
export function getFileXLSX(next: Function) {
  const fileInput = document.createElement("input");
  fileInput.type = "file";
  fileInput.accept = ".xls, .xlsx";
  fileInput.style.display = "none";
  fileInput.addEventListener("change", (event: Event) => {
    const input = event.target as HTMLInputElement;
    const file = input.files ? input.files[0] : null;
    next(file);
    fileInput.remove();
  });

  document.body.appendChild(fileInput);
  fileInput.click();
}

/** 选择本地文件中的图像 */
export function getFileImage(next: (files: FileList) => {}) {
  const fileInput = document.createElement("input");
  fileInput.type = "file";
  fileInput.accept = ".png, .jpg, .jpeg";
  fileInput.multiple = true;
  fileInput.style.display = "none";
  fileInput.addEventListener("change", (event: Event) => {
    const input = event.target as HTMLInputElement;
    next((input.files || []) as FileList);
    fileInput.remove();
  });

  document.body.appendChild(fileInput);
  fileInput.click();
}

/** 选择本地文件中的PDF文件 */
export function getFilePdf(next: (files: FileList) => void) {
  const fileInput = document.createElement("input");
  fileInput.type = "file";
  fileInput.accept = ".pdf";
  fileInput.multiple = true;
  fileInput.style.display = "none";
  fileInput.addEventListener("change", (event: Event) => {
    const input = event.target as HTMLInputElement;
    next((input.files || []) as FileList);
    fileInput.remove();
  });

  document.body.appendChild(fileInput);
  fileInput.click();
}

/** 文件转 base64 */
export function getBase64ByFile(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      const base64 = ((e.target?.result as string) || "").split(",")[1];
      resolve(base64);
    };
    reader.onerror = () => reject(`读取文件失败，请重新试试`);
  });
}

/** 文件转 buffer */
export function getBufferByFile(file: File): Promise<ArrayBuffer> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = (e) => resolve(e.target?.result as ArrayBuffer);
    reader.onerror = () => reject(`读取文件失败，请重新试试`);
  });
}

/** base64 转 buffer */
export function getBufferByBase64(base64: string): ArrayBuffer {
  const base64Data = base64.split(",")[1] || base64;

  const binaryString = atob(base64Data);
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes.buffer;
}

/** Blob转 base64 */
export function getBase64ByBlob(blob: Blob): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = (e) => {
      const base64 = ((e.target?.result as string) || "").split(",")[1];
      resolve(base64);
    };
    reader.onerror = () => reject(`读取文件失败，请重新试试`);
  });
}
